import { _decorator, AudioClip, Component } from 'cc';
const { ccclass, property, executionOrder } = _decorator;

import DragTetris_CardFunctions from "../Common/DragTetris_CardFunctions";
import { DragTetris_GameData } from "../Data/DragTetris_GameData";
import DragTetris_GamePanel from "../UI/DragTetris_GamePanel";
import DragTetris_MapManager from "./DragTetris_MapManager";
import DragTetris_GameConfig from "../Data/DragTetris_GameConfig";
import DragTetris_Grid from "../Game/DragTetris_Grid";
import UI from "../../../../Script/Manager/UI";
import DragTetris_LosePanel from "../UI/DragTetris_LosePanel";
import SSS_TimerManager from "../../../../Script/Manager/SSS_TimerManager";
import { bdlMgr } from "../../../../Script/Manager/BundleManager_S";
import { SSS_Consts } from "../../../../Script/Data/SSS_Consts";
import { DragTetris_GameStorage } from "../Data/DragTetris_GameStorage";
import { SSS_AudioManager } from 'db://assets/Script/Manager/SSS_AudioManager';

// // 慢一点执行
@ccclass('DragTetrisGameManager')
@executionOrder(101)
export default class DragTetris_GameManager extends Component {
    static Instance: DragTetris_GameManager;
    onLoad() {
        DragTetris_GameManager.Instance = this;

        DragTetris_GameStorage.initData();

        console.log(`DragTetris_GameStorage.data`, DragTetris_GameStorage.data);

        // console.log(`DragTetris_GameStorage.data.map`, DragTetris_GameStorage.data.map);


        this.Init();
    }
    Init() {
        // // 尝试恢复之前的游戏状态
        // if (DragTetris_GameStorage.hasGameStateToRestore()) {
        //     console.log("发现可恢复的游戏状态，正在恢复...");
        //     DragTetris_GameStorage.restoreGameState();
        // } else {
        DragTetris_GameData.InitData();
        // }

        // GameEventManager.AddListener();

        this.scheduleOnce(() => {
            DragTetris_MapManager.Instance.initCard();
            DragTetris_GamePanel.Instance.ShowOn();
        }, 0.01);
    }
    是否失败() {
        return !DragTetris_CardFunctions.是否可以放得下();
    }
    static async Main() {
        // console.log(`Main`);

        // 消除行列
        DragTetris_GameManager.Clear();

        DragTetris_GameData.SaveGridData();


        console.log(`DragTetris_GameManager.Instance.是否失败()`, DragTetris_GameManager.Instance.是否失败());

        if (DragTetris_GameManager.Instance.是否失败()) {
            console.log("失败-----------------");

            DragTetris_GameManager.Instance.Lose();

            return;
        }

        // 游戏状态变化后自动保存
        // DragTetris_GameStorage.saveCurrentGameState();
    }
    async Lose() {
        // CardFunctions.禁止操作(true);

        for (let x = 0; x < DragTetris_GameConfig.col; x++) {
            for (let y = 0; y < DragTetris_GameConfig.row; y++) {
                const grid: DragTetris_Grid = DragTetris_CardFunctions.GetGrid(x, y);
                let 当前格子是否是空地 = DragTetris_CardFunctions.当前格子是否是空地(grid.x, grid.y);
                if (当前格子是否是空地) {
                    grid.Flash();
                }
            }
        }


        await SSS_TimerManager.AwaitTime(1.4);

        UI.Instance.CreatePanel_sub(`DragTetris_Prefab`, `UI/DragTetris_LosePanel`, DragTetris_LosePanel);


        DragTetris_GameStorage.data.map.isEnd = true;
        DragTetris_GameStorage.saveData();
    }
    //    /** 复活 */
    Reborn() {
        DragTetris_LosePanel.Instance.ShowOff();

        let array = DragTetris_CardFunctions.获取所有非空地();

        // let scoreAll = 0;
        for (let index = 0; index < array.length; index += 2) {
            const grid: DragTetris_Grid = array[index];
            const block = grid.block
            if (block) {
                block.DestroyAnimation();
                grid.block = null;
            }
        }

        DragTetris_GameStorage.data.map.isEnd = false;
        DragTetris_GameStorage.saveData();

        DragTetris_GameData.SaveGridData();
    }
    static Clear() {
        let array_all = [];

        for (let x = 0; x < DragTetris_GameConfig.col; x++) {
            let array = DragTetris_GameManager.IsFullCol(x);
            if (array.length > 0) {
                array_all.push(array);
            }
        }

        for (let y = 0; y < DragTetris_GameConfig.row; y++) {
            let array = DragTetris_GameManager.IsFullRow(y);
            if (array.length > 0) {
                array_all.push(array);
            }
        }

        for (let index = 0; index < array_all.length; index++) {
            const element = array_all[index];
            DragTetris_GameManager.DestroyRow(element);
        }
    }
    static async DestroyRow(array) {
        let scoreAll = 0;

        for (let index = 0; index < array.length; index++) {
            const grid: DragTetris_Grid = array[index];
            const block = grid.block
            if (block) {
                block.DestroyAnimation();
                grid.block = null;
                scoreAll += DragTetris_GameData.item_score;
            }
        }

        // DragTetris_TipScorePanel.Instance.Show(`${scoreAll}`); //TODO 得分飘字


        await new Promise(res => SSS_TimerManager.Instance.scheduleOnce(res, 0.2));
        // let root = `audio/Button1`
        let root = `audio/符文碎裂`
        // let root = `audio/水音效2`
        // bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/符文碎裂`, AudioClip).then(res => {
        bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, root, AudioClip).then(res => {
            if (res) {
                SSS_AudioManager.Instance.playSFX(res, false);
                // audioEngine.setVolume(audioId, 0.6);
            }
        });
    }
    static IsFullCol(x) {
        const array = DragTetris_GameData.arrGrids[x];
        let isFull: boolean = true;
        for (let index = 0; index < array.length; index++) {
            const grid: DragTetris_Grid = array[index];
            if (grid.block === null) {
                isFull = false;
                break
            }
        }

        if (isFull) {
            return array;
        }

        return [];
    }
    static IsFullRow(y) {
        const array = [];
        let isFull: boolean = true;
        for (let x = 0; x < DragTetris_GameConfig.col; x++) {
            const grid: DragTetris_Grid = DragTetris_GameData.arrGrids[x][y];
            if (grid.block === null) {
                isFull = false;
                break;
            }
            array.push(grid);
        }

        if (isFull) {
            return array;
        }

        return [];
    }
    //    /** 新的一局 */
    static NewGame() {
        // 开始新游戏时清除保存的状态
        // DragTetris_GameStorage.clearCurrentGameState();

        // GameStorage.data.GameData = {};
        // GameStorage.data.GameData.score = 0;


        // GameStorage.data.GameData.mapData = {};
        // GameStorage.data.GameData.mapData_next = [];


        // for (let index = 0; index < 3; index++) {
        //     // let blockType = BlockType.NORMAL;
        //     // let posType = PosType.CONCTROL;
        //     let x = index;
        //     let y = -1;
        //     // let point = CardFunctions.GetRandomPoint();
        //     let color = CardFunctions.GetRandomColor();
        //     // CardFunctions.CreateBlock(blockType, posType, x, y, point, color);

        //     let id = randomRangeInt(0, 7);
        //     CardFunctions.CreateBlockGroup(id, x, y, color);
        // }
    }
    // /** 回合结束 */
    // static RoundEnd() {
    //     // DragTetris_GameData.hasnewLine = false;
    //     // DragTetris_GameData.IsCanOperate = true;
    //     // DragTetris_GameData.ContinuousEliminationNumber = 0;
    //     // DragTetris_GameStorage.ArrCardGroupsToMapData();
    //     DragTetris_GamePanel.Instance.Refresh();
    //     console.log(`回合结束`);
    //     // XXL_TipPanel.Instance.Show(`回合结束`);
    // }
    // /** 游戏结束 */
    // static GameOver() {
    //     DragTetris_GameManager.Instance.scheduleOnce(() => {
    //         // 游戏结束时清除保存的状态
    //         DragTetris_GameStorage.clearCurrentGameState();
    //         // DragTetris_GameStorage.data.GameData = {};
    //         DragTetris_GameStorage.saveData();
    //         DragTetris_GameData.arrGrids = [];
    //         DragTetris_GameData.arrCards = [];
    //         DragTetris_GameData.arrCardGroups = [];
    //         // DragTetris_GameData.arrCardGroups_next = [];
    //     }, 0.5);
    // }
    // /** 加载主场景 */
    // static LoadMainScene() {
    //     DragTetris_GameData.ClearData();
    // }
    // static ReStart() {
    //     DragTetris_GameData.ClearData();
    //     DragTetris_GamePanel.Instance.ShowOff();
    // }
    // static SaveMapData() {
    //     // DragTetris_GameStorage.data.GameData.mapData = {};
    //     DragTetris_GameStorage.saveData();
    // }
}

// /** 调试 */
window["DragTetris_GameManager"] = DragTetris_GameManager;